<template>
  <div>
    <!-- 统计卡片 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <!-- 总用户数 -->
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card shadow="hover">
          <el-statistic
            title="Total Users"
            :value="stats?.totalUsers || 0"
            :value-style="{ color: '#409EFF' }"
          >
            <template #prefix>
              <el-icon style="vertical-align: -0.125em">
                <UserFilled />
              </el-icon>
            </template>
            <template #suffix>
              <el-text type="success" size="small" style="margin-left: 8px;">
                {{ stats?.activeUsers || 0 }} active
              </el-text>
            </template>
          </el-statistic>
        </el-card>
      </el-col>

      <!-- 管理员数量 -->
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card shadow="hover">
          <el-statistic
            title="Administrators"
            :value="(stats?.totalAdmins || 0) + (stats?.totalSubAdmins || 0)"
            :value-style="{ color: '#9C27B0' }"
          >
            <template #prefix>
              <el-icon style="vertical-align: -0.125em">
                <Avatar />
              </el-icon>
            </template>
            <template #suffix>
              <el-text type="warning" size="small" style="margin-left: 8px;">
                {{ stats?.totalAdmins || 0 }} admins, {{ stats?.totalSubAdmins || 0 }} sub-admins
              </el-text>
            </template>
          </el-statistic>
        </el-card>
      </el-col>

      <!-- 充值记录 -->
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card shadow="hover">
          <el-statistic
            title="Recharge Records"
            :value="stats?.totalRechargeRecords || 0"
            :value-style="{ color: '#67C23A' }"
          >
            <template #prefix>
              <el-icon style="vertical-align: -0.125em">
                <CreditCard />
              </el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>

      <!-- 总收入 -->
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card shadow="hover">
          <el-statistic
            title="Total Revenue"
            :value="stats?.totalRevenue || 0"
            :precision="2"
            prefix="$"
            :value-style="{ color: '#F56C6C' }"
          >
            <template #prefix>
              <el-icon style="vertical-align: -0.125em">
                <Money />
              </el-icon>
            </template>
            <template #suffix>
              <el-text type="info" size="small" style="margin-left: 8px;">
                All time revenue
              </el-text>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近活动 -->
    <el-card shadow="hover">
      <template #header>
        <div style="display: flex; align-items: center; justify-content: space-between;">
          <span style="font-size: 16px; font-weight: 600;">Recent Activity</span>
          <el-button type="primary" link @click="refreshStats">
            <el-icon style="margin-right: 4px;"><Refresh /></el-icon>
            Refresh
          </el-button>
        </div>
      </template>

      <div v-if="isLoading" style="text-align: center; padding: 40px;">
        <el-icon class="is-loading" style="font-size: 32px; color: #409EFF;">
          <Loading />
        </el-icon>
        <div style="margin-top: 16px;">
          <el-text type="info">Loading activity data...</el-text>
        </div>
      </div>

      <div v-else-if="!stats || Object.keys(stats).length === 0" style="text-align: center; padding: 40px;">
        <el-icon style="font-size: 32px; color: #909399;">
          <Document />
        </el-icon>
        <div style="margin-top: 16px;">
          <el-text type="info">No activity data available</el-text>
        </div>
      </div>

      <div v-else>
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in recentActivities"
            :key="index"
            :timestamp="activity.timestamp"
            :type="activity.type"
          >
            <el-text>{{ activity.description }}</el-text>
          </el-timeline-item>
        </el-timeline>

        <div v-if="recentActivities.length === 0" style="text-align: center; padding: 20px;">
          <el-text type="info">No recent activities</el-text>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useAdminStore } from '../stores/admin'
import { ElMessage } from 'element-plus'
import {
  UserFilled,
  Avatar,
  CreditCard,
  Money,
  Document,
  Refresh,
  Loading
} from '@element-plus/icons-vue'

// Store
const adminStore = useAdminStore()

// 响应式数据
const isLoading = ref(false)

// 计算属性
const stats = computed(() => adminStore.stats)

// 模拟最近活动数据
const recentActivities = computed(() => {
  if (!stats.value) return []
  
  return [
    {
      timestamp: new Date().toLocaleString(),
      type: 'primary',
      description: `System has ${stats.value.totalUsers || 0} total users`
    },
    {
      timestamp: new Date(Date.now() - 3600000).toLocaleString(),
      type: 'success',
      description: `${stats.value.activeUsers || 0} users are currently active`
    },
    {
      timestamp: new Date(Date.now() - 7200000).toLocaleString(),
      type: 'warning',
      description: `${stats.value.totalRechargeRecords || 0} recharge records processed`
    }
  ]
})

// 刷新统计数据
async function refreshStats() {
  // 检查当前路径，避免在用户充值页面执行
  if (typeof window !== 'undefined' && window.location.pathname.includes('/user-recharge/')) {
    console.log('Skipping admin stats refresh on user recharge page')
    return
  }
  
  isLoading.value = true
  try {
    await adminStore.getSystemStats()
    ElMessage.success('Statistics refreshed successfully')
  } catch (error) {
    console.error('Failed to refresh stats:', error)
    ElMessage.error('Failed to refresh statistics')
  } finally {
    isLoading.value = false
  }
}

// 组件挂载时获取数据
onMounted(async () => {
  // 检查当前路径，避免在用户充值页面加载
  if (typeof window !== 'undefined' && window.location.pathname.includes('/user-recharge/')) {
    console.log('Skipping admin dashboard initialization on user recharge page')
    return
  }
  
  if (!stats.value || Object.keys(stats.value).length === 0) {
    await refreshStats()
  }
})
</script>

<style scoped>
.el-statistic {
  text-align: center;
}

.el-timeline {
  padding-left: 0;
}

.is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
